import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../layout/Layout.vue'

// 定义路由
const routes = [
  // 公共路由 - 不需要Layout
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/Register',
    name: 'register',
    component: () => import('../views/Register.vue'),
    meta: { title: '注册' }
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue'),
    meta: { title: '页面未找到' }
  },
  
  // 需要Layout的受保护路由
  {
    path: '/',
    component: Layout,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('../views/Home.vue'),
        meta: { title: '首页', requiresAuth: true, roles: ['merchant'] }
      },
      {
        path: 'products',
        name: 'Products',
        component: () => import('../views/Products.vue'),
        meta: { title: '商品管理', requiresAuth: true, roles: ['merchant'] }
      },
      {
        path: 'order',
        name: 'Order',
        component: () => import('../views/Order.vue'),
        meta: { title: '订单管理', requiresAuth: true, roles: ['merchant'] }
      }
    ]
  },
  {
    path: '/home',
    component: Layout,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'MerchantHome',
        component: () => import('../views/Home.vue'),
        meta: { title: '首页', requiresAuth: true, roles: ['merchant'] }
      }
    ]
  },
  // Admin路由
  {
    path: '/admin',
    component: Layout,
    meta: { requiresAuth: true, roles: ['admin'] },
    redirect: '/admin/overview',
    children: [
      {
        path: 'overview',
        name: 'Overview',
        component: () => import('../views/Admin/Overview.vue'),
        meta: { title: '数据概览', requiresAuth: true, roles: ['admin'] }
      },
      {
        path: 'merchants',
        name: 'Merchants',
        component: () => import('../views/Admin/Merchants.vue'),
        meta: { title: '商户管理', requiresAuth: true, roles: ['admin'] }
      },
      {
        path: 'announcements',
        name: 'Announcements',
        component: () => import('../views/Admin/Announcements.vue'),
        meta: { title: '公告管理', requiresAuth: true, roles: ['admin'] }
      }
    ]
  },
  // 3D数据大屏
  {
    path: '/zenosales3d',
    name: 'ZenoSales3D',
    component: () => import('../views/Admin/ZenoSales3D.vue'),
    meta: { requiresAuth: true, roles: ['admin'] }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  document.title = 'Zeno电商管理系统'

  const token = localStorage.getItem('accessToken')
  const userRolesStr = localStorage.getItem('userRoles')
  let isLoggedIn = !!token
  let userRoles = []

  // 解析角色
  if (userRolesStr) {
    try {
      userRoles = JSON.parse(userRolesStr)
    } catch (e) {
      // 解析失败，清理数据
      localStorage.removeItem('accessToken')
      localStorage.removeItem('userRoles')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('userPermissions')
      isLoggedIn = false
    }
  } else {
    isLoggedIn = false
  }

  // 1. 处理登录/注册页面
  const isPublicPage = to.path === '/login' || to.path === '/register'
  if (isPublicPage) {
    // 只有token和userRoles都存在且解析成功才算登录
    return (isLoggedIn && userRoles.length > 0) ? next('/home') : next()
  }

  // 2. 未登录用户重定向到登录页
  if (!isLoggedIn || userRoles.length === 0) {
    // 清理所有相关localStorage，避免脏数据
    localStorage.removeItem('accessToken')
    localStorage.removeItem('userRoles')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('userPermissions')
    return next('/login')
  }

  const isAdmin = userRoles.some(role => role.name === 'admin')

  // 3. 特殊处理根路径
  if (to.path === '/') {
    return isAdmin ? next('/admin') : next('/home')
  }

  // 4. 权限验证
  if (to.meta.roles) {
    const hasRequiredRole = userRoles.some(role => to.meta.roles.includes(role.name))
    if (!hasRequiredRole) {
      return isAdmin ? next('/admin') : next('/home')
    }
  }
  next()
})

export default router